package lex.dm.ui.results;

import java.awt.BorderLayout;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import org.lex.swing.ContainerFactory;

import lex.dm.DTree;

public class ResultsPane extends JPanel {
	private JTabbedPane tabPane = null;

	public ResultsPane() {
		super();
		initialize();
	}

	public void execute(String sql) {
		this.getTabPane().removeAll();
		DTree app = DTree.getApplication();
		try {
			Statement s = app.getConnection().createStatement();
			if (s.execute(sql)) {
				this.addResultSet(s.getResultSet());
				while (s.getMoreResults())
					this.addResultSet(s.getResultSet());
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void addResultSet(ResultSet rs) {
		this.addResultSet(String.valueOf(getTabPane().getTabCount() + 1), rs);
	}

	public void addResultSet(String title, ResultSet rs) {
		SingleResultSetPane pane = new SingleResultSetPane();
		pane.setResultSet(rs);
		this.getTabPane().addTab(title, pane);
		int index = tabPane.indexOfComponent(pane);
		this.getTabPane().setSelectedIndex(index);
		// this.getTabPane().setTabComponentAt( index, new CloseButton( title,
		// tabPane, pane ) );
	}

	private void initialize() {
		this.setLayout(new BorderLayout());
		this.add(getTabPane(), BorderLayout.CENTER);
	}

	private JTabbedPane getTabPane() {
		if (tabPane == null) {
			tabPane = ContainerFactory.createCloseTabPane();
			tabPane.setName(getClass().getName() + ".tab");
		}
		return tabPane;
	}
} // @jve:decl-index=0:visual-constraint="10,10"
